const express = require('express')
const router = express.Router()
const axios = require('axios')

const textMapFn = (el) => {
  return el.innerHTML.trim()
}
const textFn = (el) => el?.innerHTML.trim()
const mapJoin = (els) => {
  return els.map(textMapFn)
}
const $r = (text, reg) =>
  (text.match(reg) || ['', ''])[1]
    .trim()
    .split('/')
    .map((s) => s.trim())
function $img(url) {
  return url?.replace(/https:\/\/img\d\.doubanio\.com/, '/douban-img')
}
function $id(url) {
  const [, id] = url.match(/subject\/(\d+)\//)
  return id
}
function jsonInstance() {
  const inst = axios.create()
  inst.interceptors.request.use((config) => {
    const newConfig = {
      ...config,
      headers: { ...config.headers, Referer: 'https://movie.douban.com' },
    }
    // console.log(newConfig)
    return newConfig
  })
  return inst
}
function obj2iterator(obj) {
  const keys = Object.keys(obj)
  return keys.map((key) => [key, obj[key]])
}
function makeSearchString(obj) {
  return obj2iterator(obj)
    .filter((pair) => pair[1] !== undefined)
    .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
    .join('&')
}

// 正在上映
router.get('/on-going', async (req, res) => {
  const movies = await axios.get('https://movie.douban.com/').then(({ $$ }) => {
    const movies = $$('#screening > div.screening-bd > ul > li')
      .filter((li) => li.children.length > 0)
      .map((li) => {
        const id = $id(li.querySelector('a').href)
        const img = $img(li.querySelector('img').src)
        return {
          title: li.getAttribute('data-title'),
          id,
          img,
        }
      })
    return movies
  })
  res.json(movies)
})

router.get('/koubei', async (req, res) => {
  const movies = await axios.get('https://movie.douban.com/').then(({ $$ }) => {
    const movies = $$(
      '#billboard > div.billboard-bd > table > tbody > tr > td.title'
    ).map((item) => {
      const id = $id(item.querySelector('a').href)
      return {
        title: item.querySelector('a').innerHTML,
        id,
      }
    })
    return movies
  })
  res.json(movies)
})

// 推荐内容
router.get('/recommend', async (req, res) => {
  const movies = await axios.get('https://movie.douban.com/').then(({ $$ }) => {
    const movies = $$('#hot-gallery > ul > li').map((item) => {
      return {
        url: item.querySelector('a').href,
        img: $img(item.querySelector('a > img').src),
        title: item.querySelector('.gallery-hd h3').innerHTML,
        content: item.querySelector('.gallery-bd p').innerHTML.trim(),
      }
    })
    return movies
  })
  res.json(movies)
})

// 搜索标签
router.get('/search-tags', async (req, res) => {
  const { type, source } = req.query
  const params = { type, source }
  res.json(
    await jsonInstance()
      .get(`https://movie.douban.com/j/search_tags?${makeSearchString(params)}`)
      .then((r) => r.data)
  )
})

// 按标签搜索电影
router.get('/search-subjects', async (req, res) => {
  const {
    tag,
    type,
    sort = 'time',
    page_limit = 50,
    page_start = 0,
  } = req.query
  const params = { tag, type, sort, page_limit, page_start }
  res.json(
    await jsonInstance()
      .get(
        `https://movie.douban.com/j/search_subjects?${makeSearchString(params)}`
      )
      .then((r) => r.data.subjects)
      .then((subs) =>subs.map((s) => ({
          ...s,
          cover: $img(s.cover),
        }))
      )
  )
})

router.get('/rank', async (req, res) => {
  res.json(
    await axios.get('https://movie.douban.com/chart').then(({ $$ }) => {
      return $$(
        '#content > div > div.article > div > div > table > tbody > tr'
      ).map((item) => ({
        title: item.querySelector('a').title,
        id: $id(item.querySelector('a').href),
        img: $img(item.querySelector('img').src),
        content: item.querySelector('td:nth-child(2) > div > p').innerHTML,
        rating_nums: +item.querySelector('.rating_nums').innerHTML,
        rating_count: +item
          .querySelector('.star .pl')
          .innerHTML.match(/\d+/)[0],
      }))
    })
  )
})

router.get('/filter-params', async (req, res) => {
  res.json(
    // await axios.get('https://movie.douban.com/tag').then(({ $$ }) => {
    //   const types = $$(
    //     '#app > div > div.article > div.tags > ul:nth-child(1) > li > span'
    //   ).map(({ innerHTML }) => innerHTML?.trim())
    //   const genres = $$(
    //     '#app > div > div.article > div.tags > ul:nth-child(2) > li > span'
    //   ).map(({ innerHTML }) => innerHTML?.trim())
    //   const countries = $$(
    //     '#app > div > div.article > div.tags > ul:nth-child(3) > li > span'
    //   ).map(({ innerHTML }) => innerHTML?.trim())
    //   const year_ranges = $$(
    //     '#app > div > div.article > div.tags > ul:nth-child(4) > li > span'
    //   ).map(({ innerHTML }) => innerHTML?.trim())
    //   const specials = $$(
    //     '#app > div > div.article > div.tags > ul:nth-child(5) > li > span'
    //   ).map(({ innerHTML }) => innerHTML?.trim())
    //   return { types, genres, countries, year_ranges, specials }
    // })

    {
      tag_categories: [
        ['全部形式', '电影', '电视剧', '综艺', '动漫', '纪录片', '短片'],
        [
          '全部类型',
          '剧情',
          '喜剧',
          '动作',
          '爱情',
          '科幻',
          '动画',
          '悬疑',
          '惊悚',
          '恐怖',
          '犯罪',
          '同性',
          '音乐',
          '歌舞',
          '传记',
          '历史',
          '战争',
          '西部',
          '奇幻',
          '冒险',
          '灾难',
          '武侠',
          '情色',
        ],
        [
          '全部地区',
          '中国大陆',
          '欧美',
          '美国',
          '中国香港',
          '中国台湾',
          '日本',
          '韩国',
          '英国',
          '法国',
          '德国',
          '意大利',
          '西班牙',
          '印度',
          '泰国',
          '俄罗斯',
          '伊朗',
          '加拿大',
          '澳大利亚',
          '爱尔兰',
          '瑞典',
          '巴西',
          '丹麦',
        ],
        [
          '全部年代',
          '2022',
          '2021',
          '2020',
          '2019',
          '2010年代',
          '2000年代',
          '90年代',
          '80年代',
          '70年代',
          '60年代',
          '更早',
        ],
        [
          '全部特色',
          '经典',
          '青春',
          '文艺',
          '搞笑',
          '励志',
          '魔幻',
          '感人',
          '女性',
          '黑帮',
          '',
        ],
      ],
      tabs: [
        ['U', '近期热门'],
        ['T', '标记最多'],
        ['S', '评分最高'],
        ['R', '最新上映'],
      ],
      sort: 'U',
      range: [0, 10],
      yearMap: {
        '2018年以后': [2019, 9999],
        2022: [2022, 2022],
        2021: [2021, 2021],
        2020: [2020, 2020],
        2019: [2019, 2019],
        '2010年代': [2010, 2019],
        '2000年代': [2e3, 2009],
        '90年代': [1990, 1999],
        '80年代': [1980, 1989],
        '70年代': [1970, 1979],
        '60年代': [1960, 1969],
        更早: [1, 1959],
      },
    }
  )
})

router.get('/filter', async (req, res) => {
  const {
    sort = 'U',
    tags,
    genres,
    countries,
    year_range,
    start = 0,
    range = '0,10',
  } = req.query

  const params = { sort, tags, genres, countries, year_range, start, range }

  res.json(
    await jsonInstance()
      .get(
        'https://movie.douban.com/j/new_search_subjects?' +
          makeSearchString(params)
      )
      .then((r) => {
        if (r.data.data === undefined) {
          throw new Error(r.data.msg)
        } else {
          return r.data.data
        }
      })
      .then((movies) => movies.map((m) => ({ ...m, cover: $img(m.cover) })))
      .catch((error) => ({ error: error.message }))
  )
})

router.get('/m/:id', async (req, res) => {
  const { id } = req.params
  res.json(
    await axios
      .get('https://movie.douban.com/subject/' + id + '/')
      .then(({ $$, $, text }) => {
        return {
          id,
          title: $('h1 span:nth-child(1)').innerHTML.trim(),
          year: $('h1 span:nth-child(2)').innerHTML.trim().replace(/[()]/g, ''),
          directors: mapJoin($$('[rel="v:directedBy"]')),
          scripts: mapJoin($$('#info > span:nth-child(3) > span.attrs > a')),
          actors: mapJoin($$('[rel="v:starring"]')),
          genres: mapJoin($$('[property="v:genre"]')),
          homepage: textFn($('#info > a')),
          nations: $r(
            text,
            /<span class="pl">制片国家\/地区:<\/span>(.*)<br\/>/
          ),
          langs: $r(text, /<span class="pl">语言:<\/span>(.*)<br\/>/),
          issueDates: mapJoin($$('[property="v:initialReleaseDate"]')),
          aliases: $r(text, /<span class="pl">又名:<\/span>(.*)<br\/>/),
          runTime: $('[property="v:runtime"]').getAttribute('content'),
          ratingAvg: textFn($('[property="v:average"]')),
          ratings: mapJoin($$('.rating_per')),
          summary: textFn($('[property="v:summary"]')),
          image: $('[rel="v:image"]').getAttribute('src'),
          trailor: {
            href: $('.label-trailer > .related-pic-video').href,
            image: $img(
              ((
                $('.label-trailer > .related-pic-video')?.style
                  .backgroundImage || ''
              ).match(/^url\(([^)]*)\)$/) || [])[1]
            ),
          },
          shortVideo: {
            href: $('.label-short-video > .related-pic-video')?.getAttribute(
              'href'
            ),
            image: $img(
              ((
                $('.label-short-video > .related-pic-video')?.style
                  .backgroundImage || ''
              ).match(/^url\(([^)]*)\)$/) || [])[1]
            ),
          },
          images: $$('.related-pic-bd img').map((el) => el.getAttribute('src')),
        }
      })
  )
})

module.exports = router
